package com.huawei.leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Code16 {

    public static void main(String[] args) {
        int[] nums = {-1, 2, 1, -4};
        System.out.println(new Code16().threeSumClosest(nums, 4));
    }

    /**
     * 3 <= nums.length <= 1000
     * -1000 <= nums[i] <= 1000
     * -10^4 <= target <= 10^4
     *
     * @param nums
     * @param target
     * @return
     */
    public int threeSumClosest(int[] nums, int target) {
        Map<Integer, List<Integer[]>> map = new HashMap<>();
        for (int i = 0; i < nums.length - 2; i++) {
            for (int j = i + 1; j < nums.length - 1; j++) {
                for (int k = j + 1; k < nums.length; k++) {
                    int sum = nums[i] + nums[j] + nums[k];
                    List<Integer[]> list = map.getOrDefault(sum, new ArrayList<>());
                    Integer[] arr = {i, j, k};
                    list.add(arr);
                    map.put(sum, list);
                }
            }
        }
        int min = Integer.MAX_VALUE;
        int ans = 0;
        Iterator<Integer> iterator = map.keySet().iterator();

        while (iterator.hasNext()) {
            Integer next = iterator.next();
            int abs = Math.abs(next - target);
            if (abs < min) {
                min = abs;
                ans = next;
            }
        }
        return ans;
    }
}

